package com.hucc.redislock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 摇号器
 */
public class Yaohao {
    private Semaphore semaphore = new Semaphore(0);

    /**
     * 摇号， 摇号成功或规定时间没摇到号，结束，其他阻塞
     * timeout 摇号时间，单位毫秒
     */
    boolean turn(long timeout) {
        try {
            return semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 摇号 可响应中断
     */
    boolean turnInterruptibly(long timeout) throws InterruptedException {
        return semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 清空号
     */
    boolean clear() {
        return semaphore.tryAcquire();
    }

    /**
     * 放号
     */
    void putIn() {
        if (semaphore.availablePermits() <= 0) {
            semaphore.release();
        }
    }
}
